Angular HttpClient மாட்யூல்
Angular HttpClient மாட்யூல் ஒரு சக்திவாய்ந்த HTTP கிளையண்ட் API-ஐ வழங்குகிறது, இது Angular பயன்பாடுகளுக்குள் வெளிப்புற HTTP சேவைகளுடன் தொடர்பு கொள்ள பயன்படுத்தப்படுகிறது. இது XMLHttpRequest API-க்கு மேலாக அதிக செயல்திறன் மற்றும் சிறந்த பிழைக் கையாளுதலுடன் ஒரு எளிமையான வழியை வழங்குகிறது.
HttpClient கிளாஸ் GET, POST, PUT, DELETE மற்றும் பிற HTTP முறைகளை ஆதரிக்கிறது. இது Observables ஐப் பயன்படுத்தி எதிர்வினை நிரலாக்கத்தை ஆதரிக்கிறது, இது வலுவான பிழைக் கையாளுதல், ரத்து செய்யும் திறன் மற்றும் பல HTTP கோரிக்கைகளை இணைக்கும் திறன் ஆகியவற்றை வழங்குகிறது.
HTTP அடிப்படைகள்
கிளையண்ட்: JSON தரவைப் பெறவும் அனுப்பவும் HttpClient பயன்படுத்தவும்.
Observables: HTTP முறைகள் Observables வழங்குகின்றன. subscribe() அல்லது async pipe பயன்படுத்தவும்.
பயனர் அனுபவம்: ஏற்றுதல் காட்டவும் மற்றும் தெளிவான பிழை செய்திகள் வழங்கவும்.
ஒரு முறை வழங்கவும்: bootstrap-இல் provideHttpClient() பதிவு செய்யவும்.
HTTP கிளையண்ட் அமைப்பு
import { provideHttpClient, HttpClient } from '@angular/common/http';
// Bootstrap
// bootstrapApplication(App, { providers: [provideHttpClient()] });
// Use in a component
// http.get<User[]>('/api/users').subscribe({ அடுத்தது: d => users = d });
Jassif Team குறிப்புகள்:
HTTP தர்க்கத்தை இணைக்க Services, கோரிக்கைகளுக்குப் பிறகு வழிசெலுத்தலுக்கு Router, மற்றும் பட்டியல்கள் மற்றும் நிலைகளை வழங்குவதற்கு Templates பற்றி காண்க.
Bootstrap-இல் provideHttpClient() மூலம் கிளையண்டை வழங்கவும்.
லோடிங் மற்றும் பிழை நிலைகளுடன் தடையற்ற UI-களைப் பயன்படுத்தவும்; பொது APIs-ஐ அழைக்கும் போது CORS-ஐப் பற்றி கவனமாக இருங்கள்.
அடிப்படை URL & சூழல்: API அடிப்படை URL/கட்டமைப்பை ஒரு டோக்கன் அல்லது மாறிலியில் மையப்படுத்தவும் மற்றும் சேவைகளில் மீண்டும் பயன்படுத்தவும்.
பாதுகாப்பு: நம்பமுடியாத URL பகுதிகளைச் சரிபார்க்கவும்; கோரிக்கை URLs-இல் மூல பயனர் உள்ளீட்டை நேரடியாக இடைச்செருகுவதைத் தவிர்க்கவும்.
GET கோரிக்கைகள்
http.get<T>() முறையைப் பயன்படுத்தி தரவைப் பெறவும்.
பயனர் அனுபவத்திற்காக ஏற்றுதல் மற்றும் பிழை நிலையைக் கண்காணிக்கவும்.
சந்தாவுக்குள் கூறு நிலையைப் புதுப்பிக்கவும்.
GET கோரிக்கை மாதிரி
loading = true; error = '';
http.get<User[]>('/api/users').subscribe({
அடுத்தது: d => { users = d; loading = false; },
error: () => { error = 'Failed to load'; loading = false; }
});
முழு GET எடுத்துக்காட்டு
import { bootstrapApplication } from '@angular/platform-browser';
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { provideHttpClient, HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
<h3>HttpClient</h3>
<button (click)="load()">Load Users</button>
<p *ngIf="loading">Loading...</p>
<p *ngIf="error" style="color:crimson">{{ error }}</p>
<ul>
<li *ngFor="let u of users">{{ u.name }} ({{ u.email }})</li>
</ul>
`
})
export class App {
http = inject(HttpClient);
users: any[] = [];
loading = false;
error = '';
load() {
this.loading = true;
this.error = '';
this.http.get<any[]>('https://jsonplaceholder.typicode.com/users')
.subscribe({
அடுத்தது: (data) => { this.users = data; this.loading = false; },
error: () => { this.error = 'Failed to load users'; this.loading = false; }
});
}
}
bootstrapApplication(App, { providers: [provideHttpClient()] });
எடுத்துக்காட்டு விளக்கம்:
provideHttpClient(): HTTP கோரிக்கைகள் வேலை செய்வதற்காக HttpClient-ஐ பதிவு செய்கிறது.
inject(HttpClient): standalone கூறில் HTTP கிளையண்டை மீட்டெடுக்கிறது.
GET முறை: http.get<any[]>(url) ஒரு Observable-ஐ வழங்குகிறது; subscribe() வெற்றியில் பயனர்களை அமைக்கிறது மற்றும் தோல்வியில் பிழை செய்தி.
பயனர் அனுபவக் கொடிகள்: ஏற்றுதல் மற்றும் பிழை செய்திகள் டெம்ப்ளேட்டை இயக்குகின்றன.
POST கோரிக்கைகள்
http.post<T>() முறையைப் பயன்படுத்தி புதிய தரவை உருவாக்கவும்.
நகல்களைத் தடுக்க அனுப்பும் போது பொத்தானை முடக்கவும்.
திரும்பப் பெறப்பட்ட முடிவு அல்லது பிழை செய்தியை வழங்கவும்.
POST கோரிக்கை மாதிரி
loading = true; error = ''; result = null;
http.post<Post>('/api/posts', { title, body }).subscribe({
அடுத்தது: r => { result = r; loading = false; },
error: () => { error = 'Failed to create'; loading = false; }
});
முழு POST எடுத்துக்காட்டு
import { bootstrapApplication } from '@angular/platform-browser';
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { provideHttpClient, HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
<h3>HttpClient POST</h3>
<button (click)="createPost()" [disabled]="loading">Create Post</button>
<p *ngIf="loading">Sending...</p>
<p *ngIf="error" style="color:crimson">{{ error }}</p>
<div *ngIf="result">
<p>Created Post ID: {{ result.id }}</p>
<p>Title: {{ result.title }}</p>
</div>
`
})
export class App {
http = inject(HttpClient);
loading = false;
error = '';
result: any = null;
createPost() {
this.loading = true;
this.error = '';
this.result = null;
this.http.post<any>('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
}).subscribe({
அடுத்தது: (res) => { this.result = res; this.loading = false; },
error: () => { this.error = 'Failed to create post'; this.loading = false; }
});
}
}
bootstrapApplication(App, { providers: [provideHttpClient()] });
எடுத்துக்காட்டு விளக்கம்:
POST முறை: http.post<T>(url, body) JSON தரவை அனுப்புகிறது மற்றும் உருவாக்கப்பட்ட பொருளை வழங்குகிறது.
அனுப்பும் போது முடக்கவும்: நகல் சமர்ப்பிப்புகளைத் தடுக்க பொத்தான் ஏற்றுதல் நிலையுடன் bind செய்கிறது.
முடிவு: வெற்றியில், திரும்பப் பெறப்பட்ட முடிவைக் காட்டவும்; பிழையில், தெளிவான செய்தியைக் காட்டவும்.
POST சிறந்த நடைமுறைகள்:
உள்ளீட்டை சரிபார்க்கவும்: சர்வர் எதிர்பார்க்கும் சரிபார்க்கப்பட்ட payload-ஐ அனுப்பவும்; புலம் பிழைகளைத் தெளிவாகக் காட்டவும்.
Idempotency: நகல் சமர்ப்பிப்புகளைத் தவிர்க்கவும்; பொருத்தமானதாக இருந்தால் அனுப்பும் போது மற்றும் வெற்றிக்குப் பிறகு பொத்தானை முடக்கப்பட்டதாக வைத்திருங்கள்.
பிழைகளைக் கையாளவும்: தெளிவான பிழை செய்தியைக் காட்டவும் மற்றும் பயனர் மீண்டும் முயற்சிக்க அனுமதிக்கவும்.
பிழைக் கையாளுதல்
எப்போதும் ஒரு உதவியான பிழை செய்தியைக் காட்டவும் மற்றும் மீண்டும் முயற்சிக்க பயனரை அனுமதிக்கவும்.
மீண்டும் முயற்சி vs விரைவாகத் தோல்வியுறுவதை முடிவு செய்ய நிலை குறியீடுகளைச் சரிபார்க்கவும்.
பயனர் இடைமுகத்தை ஏற்றுதல் நிலையுடன் பதிலளிக்கும் வகையில் வைத்திருங்கள்.
பிழைக் கையாளுதல் மாதிரி
error = ''; loading = true;
http.get('/api/data').subscribe({
அடுத்தது: r => { data = r; loading = false; },
error: err => { error = `Request failed (status ${'{'}err?.status ?? 'unknown'{}})`; loading = false; }
});
முழு பிழைக் கையாளுதல் எடுத்துக்காட்டு
import { bootstrapApplication } from '@angular/platform-browser';
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { provideHttpClient, HttpClient, withInterceptors, HttpResponse, HttpErrorResponse, HttpRequest, HttpHandlerFn } from '@angular/common/http';
import { of, throwError } from 'rxjs';
// Fake HTTP interceptor so the demo works without external network calls
function mockHttp(req: HttpRequest<any>, அடுத்தது: HttpHandlerFn) {
if (req.method === 'GET' && req.url.includes('jsonplaceholder.typicode.com/usersx')) {
return throwError(() => new HttpErrorResponse({ status: 404, statusText: 'Not Found', url: req.url }));
}
if (req.method === 'GET' && req.url.includes('jsonplaceholder.typicode.com/users')) {
const body = [
{ id: 1, name: 'Leanne Graham', email: 'leanne@example.com' },
{ id: 2, name: 'Ervin Howell', email: 'ervin@example.com' }
];
return of(new HttpResponse({ status: 200, body }));
}
return அடுத்தது(req);
}
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
styles: [`
button { margin-right: 8px; }
.error { color: crimson; }
.ok { color: seagreen; }
`],
template: `
<h3>HTTP Error Handling</h3>
<div>
<button (click)="loadOk()" [disabled]="loading">Load OK</button>
<button (click)="loadFail()" [disabled]="loading">Load Fail</button>
<button (click)="retry()" [disabled]="!lastAction || loading">Retry</button>
</div>
<p *ngIf="loading">Loading...</p>
<p *ngIf="error" class="error">{{ error }}</p>
<p *ngIf="!error && data" class="ok">Loaded {{ isArray(data) ? data.length + ' items' : '1 item' }}</p>
<ul *ngIf="isArray(data)">
<li *ngFor="let u of data">{{ u.name }} ({{ u.email }})</li>
</ul>
`
})
export class App {
http = inject(HttpClient);
loading = false;
error = '';
data: any[] | null = null;
lastAction = '';
isArray(value: unknown): value is any[] { return Array.isArray(value as any); }
fetch(url: string): void {
this.loading = true;
this.error = '';
this.data = null;
this.http.get<any[]>(url).subscribe({
அடுத்தது: (res) => { this.data = res; this.loading = false; },
error: (err) => {
const status = err?.status ?? 'unknown';
this.error = `Request failed (status ${status}). Please try again.`;
this.loading = false;
}
});
}
loadOk() {
this.lastAction = 'ok';
this.fetch('https://jsonplaceholder.typicode.com/users');
}
loadFail() {
this.lastAction = 'fail';
this.fetch('https://jsonplaceholder.typicode.com/usersx');
}
retry() {
if (this.lastAction === 'ok') this.loadOk();
else if (this.lastAction === 'fail') this.loadFail();
}
}
bootstrapApplication(App, { providers: [provideHttpClient(withInterceptors([mockHttp]))] });
பிழைக் கையாளுதல் விளக்கம்:
பிழை செய்தி: err.status-இலிருந்து ஒரு உதவியான செய்தியை உருவாக்கவும்; UI-ஐ ஏற்றுதல் நிலையுடன் பதிலளிக்கும் வகையில் வைத்திருங்கள்.
மீண்டும் முயற்சி: lastAction-ஐ சேமிக்கவும் மற்றும் கடைசி கோரிக்கையை மீண்டும் இயக்க retry() பொத்தானை இணைக்கவும்.
வெற்றி vs தோல்வி: தனி முறைகள் வெற்றி மற்றும் தோல்வி ஓட்டங்களை நிரூபிக்க உதவுகின்றன.
பிழைக் கையாளுதல் சிறந்த நடைமுறைகள்:
பிழைகளை மறைக்காதீர்கள்: பயனர்களுக்கு ஒரு உதவியான செய்தியைக் காட்டவும் மற்றும் பிழைத்திருத்தத்திற்கான விவரங்களைப் பதிவு செய்யவும்.
மீண்டும் முயற்சி உத்தி: சீரற்ற பிழைகளில் மட்டுமே மீண்டும் முயற்சிக்கவும் (எ.கா., 5xx); 4xx கிளையண்ட் பிழைகளை மீண்டும் முயற்சிப்பதைத் தவிர்க்கவும்.
பின்னூட்டம்: தெளிவான பிழை செய்தியைக் காட்டவும் மற்றும் பயனர் மீண்டும் முயற்சிக்க அனுமதிக்கவும்.
பழைய கோரிக்கைகளை ரத்து செய்யவும்: விரைவான உள்ளீட்டில், பந்தயங்களைத் தவிர்ப்பதற்கு சமீபத்திய ஸ்ட்ரீமுக்கு மாறவும்.
Interceptors: கூறுகளை மெல்லியதாக வைத்திருப்பதற்காக auth headers, logging மற்றும் retry-ஐ மையப்படுத்தவும்.
HTTP Interceptors
ஒவ்வொரு HTTP கோரிக்கை/பதிலிலும் குறுக்கு-வெட்டு தர்க்கத்தை இயக்கவும் (எ.கா., authentication headers, logging).
provideHttpClient(...) உடன் bootstrap-இல் ஒரு முறை பதிவு செய்யவும்.
Interceptor அமைப்பு
import { HttpInterceptorFn, provideHttpClient, withInterceptors } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, அடுத்தது) => {
const cloned = req.clone({ setHeaders: { Authorization: 'Bearer TOKEN' } });
return அடுத்தது(cloned);
};
bootstrapApplication(App, {
providers: [provideHttpClient(withInterceptors([authInterceptor]))]
});
Interceptor எடுத்துக்காட்டு
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
@Component({ selector: 'app-root', standalone: true, template: `<p>Interceptors demo</p>` })
export class App {}
bootstrapApplication(App, {
providers: [provideHttpClient(withInterceptors([]))]
});
Interceptors விளக்கம்:
withInterceptors([...]): அனைத்து HTTP கோரிக்கைகளுக்கும் இண்டர்செப்டர் செயல்பாடுகளைப் பதிவு செய்கிறது.
Interceptor: ஒரு செயல்பாடு (req, அடுத்தது) கோரிக்கையை மாற்ற req.clone(...) செய்ய முடியும், பின்னர் அடுத்தது(req) அழைக்கிறது.
provideHttpClient(): HttpClient-ஐ இயக்குகிறது மற்றும் bootstrap-இல் interceptors-ஐ உருவாக்குகிறது.
HTTP முறைகள் ஒப்பீடு
| முறை | நோக்கம் | எடுத்துக்காட்டு |
|---|---|---|
| GET | தரவைப் படிக்கவும் (பாதுகாப்பான, மாறாத) | http.get('/api/users') |
| POST | புதிய வளத்தை உருவாக்கவும் | http.post('/api/users', data) |
| PUT | வளத்தை முழுமையாக மாற்றவும் | http.put('/api/users/1', data) |
| PATCH | பகுதி புதுப்பிப்பு | http.patch('/api/users/1', data) |
| DELETE | வளத்தை நீக்கவும் | http.delete('/api/users/1') |
| HEAD | தலைப்புகள் மட்டுமே | http.head('/api/users') |